package com.feiyisuo.sso.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequestEntityConverter;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@Slf4j
@Component
public class GitEeAuthenticationUserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {


    private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
    private final Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter();

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
        ResponseEntity<SsoOAuth2User> response = this.getResponse(request);
        SsoOAuth2User oauth2User = Objects.requireNonNull(response.getBody());
        String name = oauth2User.getName();
        log.info("oauth获取到得用户名称：{}", name);
        //根据用户名称查询对应数据
        oauth2User.setPreferredUsername("zhangSan");
        //todo 判断用户是否存在
        //todo 查询出对应权限
        return oauth2User;
    }


    private ResponseEntity<SsoOAuth2User> getResponse(RequestEntity<?> request) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
            return restTemplate.exchange(request, SsoOAuth2User.class);
        } catch (RestClientException ex) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
                    "尝试从gitEe获取用户信息失败: " + ex.getMessage(), null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
        }
    }
}
